<template>
  <view class="countdown">
    <text>剩余时间:</text>
    <text class="time">{{ hours }}</text>
    <text class="colon">:</text>
    <text class="time">{{ minutes }}</text>
    <text class="colon">:</text>
    <text class="time">{{ seconds }}</text>
  </view>
</template>

<script>
export default {
  props: {
    endTime: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      hours: '00',
      minutes: '00',
      seconds: '00',
      timer: null
    }
  },
  mounted() {
    this.updateCountdown()
    this.timer = setInterval(() => {
      this.updateCountdown()
    }, 1000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    updateCountdown() {
      const end = new Date(this.endTime).getTime()
      const now = new Date().getTime()
      const diff = end - now
      
      if (diff <= 0) {
        this.hours = '00'
        this.minutes = '00'
        this.seconds = '00'
        clearInterval(this.timer)
        this.$emit('timeout')
        return
      }
      
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diff % (1000 * 60)) / 1000)
      
      this.hours = hours.toString().padStart(2, '0')
      this.minutes = minutes.toString().padStart(2, '0')
      this.seconds = seconds.toString().padStart(2, '0')
    }
  }
}
</script>

<style scoped>
.countdown {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #FF4500;
}

.time {
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  background-color: #FF4500;
  color: #FFF;
  border-radius: 3px;
  margin: 0 2px;
}

.colon {
  margin: 0 2px;
}
</style>